package com.yin.waimai.controller;

import com.yin.waimai.dto.RegistrationRequestDTO;
import com.yin.waimai.dto.UserDTO; // 我们将创建一个 UserDTO 用于返回用户信息，避免暴露密码等敏感信息
import com.yin.waimai.model.User;
import com.yin.waimai.service.UserService;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/v1/auth") // 认证相关的API可以统一前缀
public class AuthController {

    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    private final UserService userService;
    private final AuthenticationManager authenticationManager;

    @Autowired
    public AuthController(UserService userService, AuthenticationManager authenticationManager) {
        this.userService = userService;
        this.authenticationManager = authenticationManager;
    }

    @PostMapping("/register")
    public ResponseEntity<?> registerUser(@Valid @RequestBody RegistrationRequestDTO registrationRequest) {
        logger.info("Received registration request for username: {}", registrationRequest.getUsername());
        try {
            User registeredUser = userService.registerNewUser(registrationRequest);
            // 注册成功后，通常不返回完整的 User 实体（特别是密码）
            // 创建一个 UserDTO 来返回必要的信息
            UserDTO userDto = convertToDto(registeredUser);
            logger.info("User {} registered successfully.", userDto.getUsername());
            // 返回 201 Created 状态码和用户信息 (不含密码)
            return ResponseEntity.status(HttpStatus.CREATED).body(userDto);
        } catch (IllegalStateException e) {
            // 例如用户名已存在等业务异常
            logger.warn("Registration failed for {}: {}", registrationRequest.getUsername(), e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
        } catch (Exception e) {
            // 其他未知异常
            logger.error("An unexpected error occurred during registration for username {}: {}", registrationRequest.getUsername(), e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An unexpected error occurred during registration.");
        }
    }

    // 辅助方法：将 User 实体转换为 UserDTO
    private UserDTO convertToDto(User user) {
        if (user == null) {
            return null;
        }
        UserDTO dto = new UserDTO();
        dto.setId(user.getId());
        dto.setUsername(user.getUsername());
        // 从 User 实体中的 roles (Set<String>) 转换为 UserDTO 中的 roles (Set<String> 或 List<String>)
        // UserDetails.getAuthorities() 返回的是 Collection<? extends GrantedAuthority>
        // 我们 User 实体中的 roles 就是 Set<String>，可以直接用
        dto.setRoles(user.getRoles());
        // dto.setEmail(user.getEmail()); // 如果有邮箱
        // 设置其他你希望在注册成功后返回的非敏感信息
        return dto;
    }

    // （可选）登录API，虽然Spring Security的formLogin处理了，但有时也需要自定义登录API返回Token等
    // @PostMapping("/login")
    // public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequestDTO loginRequest) {
    //     // ... 登录逻辑，通常涉及 AuthenticationManager ...
    // }
    
    @PostMapping("/admin-login")
    public ResponseEntity<?> adminLogin(@RequestBody Map<String, String> loginRequest) {
        logger.info("Received admin login request for username: {}", loginRequest.get("username"));
        try {
            // 创建认证令牌
            UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
                    loginRequest.get("username"), 
                    loginRequest.get("password")
            );
            
            // 执行认证
            Authentication authentication = authenticationManager.authenticate(authToken);
            
            // 如果认证成功，设置认证信息到安全上下文
            SecurityContextHolder.getContext().setAuthentication(authentication);
            
            // 检查是否有ADMIN角色
            boolean isAdmin = authentication.getAuthorities().stream()
                    .anyMatch(a -> a.getAuthority().equals("ROLE_ADMIN"));
            
            if (!isAdmin) {
                logger.warn("User {} attempted to login as admin but lacks ADMIN role", loginRequest.get("username"));
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Access denied: Admin role required");
            }
            
            // 返回成功响应
            Map<String, Object> response = new HashMap<>();
            response.put("username", authentication.getName());
            response.put("roles", authentication.getAuthorities().stream()
                    .map(GrantedAuthority::getAuthority)
                    .collect(Collectors.toList()));
            
            logger.info("Admin login successful for user: {}", authentication.getName());
            return ResponseEntity.ok(response);
            
        } catch (AuthenticationException e) {
            logger.warn("Admin login failed for username {}: {}", loginRequest.get("username"), e.getMessage());
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid username or password");
        }
    }
}